package com.peng.leetcode.tree;

import java.util.*;

/**
 * SubtreeWithAllDeepest
 * <p>
 * 865. 具有所有最深节点的最小子树
 *
 * @author: lupeng6
 * @create: 2021/2/5 14:42
 */
public class SubtreeWithAllDeepest2 {

    public static void main(String[] args) {
        Integer[] arr = {0,1,2,3,7,4,5,6,8,null,9};
        TreeNode treeNode = TreeMain.array2tree(arr);
        TreeNode node = new SubtreeWithAllDeepest2().subtreeWithAllDeepest(treeNode);
        System.out.println(node);
    }

    private Map<TreeNode, Integer> depth = new HashMap<>();
    private int maxDepth = 0;

    public TreeNode subtreeWithAllDeepest(TreeNode root) {
        if (root == null) {
            return null;
        }
        if (root.left == null && root.right == null) {
            return root;
        }
        initNodeDepth(root);
        TreeNode node = dfsGetAnswer(root);
        return node;
    }

    TreeNode dfsGetAnswer(TreeNode node) {
        if (node == null || depth.get(node) == maxDepth) {
            return node;
        }
        TreeNode left = dfsGetAnswer(node.left);
        TreeNode right = dfsGetAnswer(node.right);
        if (left != null && right != null) {
            return node;
        }
        if (left != null) {
            return left;
        }
        if (right != null) {
            return right;
        }
        return null;
    }

    void initNodeDepth(TreeNode root) {
        // 层级遍历 记录父子关系, 节点深度
        depth.put(null, -1);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            maxDepth++;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                depth.put(node, maxDepth);
                if (node.left != null) {
                    queue.offer(node.left);
                }

                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
    }


}
